package com.speed.temp;

import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

import com.jfinal.kit.Prop;
import com.jfinal.kit.PropKit;
import com.speed.entity.Activtites;
import com.speed.util.SmsTempData;

import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;

public enum SmsTempFactory {

	INSTANCE;
	private SmsTempFactory() {
		List<Activtites> activtites = Activtites.MODEL_DAO.find("select id from " + Activtites.TABLE_NAME);
		for (Activtites a : activtites) {
			Integer id = a.get(Activtites.ID);
			try {
				Prop prop = PropKit.use(PATH + "smsTemp" + id + ".txt");
				map.put(id, prop);
			} catch (Exception e) {
				//System.out.println(e);
			}
		}
	}

	private String PATH = "com/speed/temp/";
	private Map<Integer, Prop> map = new HashMap<Integer, Prop>();

	public List<String> getTempName(Integer keyID) {
		List<String> keywords = new ArrayList<String>();
		Prop prop = map.get(keyID);
		if(prop == null){
			return null;
		}
		Properties properties = prop.getProperties();
		Set<String> names = properties.stringPropertyNames();
		for (String name :names) {
			System.out.println("模板" + keyID + " { " + name + " }");
			keywords.add(name);
		}
		return keywords;
	}

	/**
	 * 根据活动ID和模板关建字输出短信内容
	 * 
	 * @param keyID
	 * @param keyword
	 * @param data
	 * @return
	 */
	public String getContent(Integer keyID, String keyword, SmsTempData data) {
		Prop prop = map.get(keyID);
		String temp = prop.get(keyword);
		try {
			Configuration cfg = new Configuration();
			StringTemplateLoader stl = new StringTemplateLoader();
			stl.putTemplate("1", temp);
			cfg.setTemplateLoader(stl);
			Template template = cfg.getTemplate("1");
			StringWriter writer = new StringWriter();
			template.process(data, writer);
			System.out.println(writer.toString());
			return writer.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "";
	}
}
